package com.gitee.hermer.engine.jars.core.xauth.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.gitee.hermer.boot.jee.commons.utils.StringUtils;
import com.gitee.hermer.engine.jars.core.xauth.config.XAuthProperties;
import com.gitee.hermer.engine.jars.dependent.dsm.IEnginePropertiesAware;
import com.jc.support.auth.web.interceptor.DefaultBizAuthenticationHandlerInterceptor;
import com.jc.support.auth.web.util.AccountUtils;
import com.jc.support.user.sso.service.SSOAccountService;
import com.jc.xauth.web.interceptor.AuthenticationHandlerInterceptor;

public class EngineAuthenticationHandlerInterceptor extends AuthenticationHandlerInterceptor implements IEnginePropertiesAware<XAuthProperties>{

	private XAuthProperties properties;
	@Autowired
	private SSOAccountService ssoAccountService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String whiteStr = properties.getWhiteList();
		if(StringUtils.isNotBlank(whiteStr)){
			String[] whiteList = StringUtils.split(whiteStr, ",");
			for (String whiteIp : whiteList) {
				if(StringUtils.trimEquals(whiteIp, request.getRemoteAddr()) || isLocalIp(request.getRemoteAddr())){
					return true;
				}
			}
		}
		return super.preHandle(request, response, handler);
	}

	protected boolean isAccessAllowed(HttpServletRequest request, HttpServletResponse response, boolean strictlyAuthc)
	{
		Subject subject = getSubject(request, response);
		if (strictlyAuthc) {
			return subject.isAuthenticated();
		}
		if (subject.getPrincipal() == null) {
			return false;
		}
		if ((!subject.isAuthenticated()) && (this.ssoAccountService.isSuperAdminByAccountCode(AccountUtils.getCurrentAccount().getAccountCode()))) {
			return false;
		}
		return true;
	}


	private  boolean isLocalIp(String ip){  
		return false;//return ip.equals("127.0.0.1")||ip.equals("localhost")||ip.equals("0:0:0:0:0:0:0:1");  
	}


	@Override
	@Autowired
	public void setProperties(XAuthProperties properties) {
		this.properties = properties;
	}  

}

